# -*- coding:utf-8 -*-

from com.zzh.utils.dbUtils import MysqlUtils
from com.zzh.utils.table2JSON import Table2Json
import time
local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))

class HistoryDao(object):
    def __init__(self):
        self.conn = MysqlUtils.get_mysql_connections()

    def add_history(self, his_info):
        """

        :param his_info:
        :param user_id:
        :return:
        """
        user_id = his_info['user_id']
        user_ip = his_info['user_ip']
        history_keyword = his_info['history_keyword']
        history_type = his_info['history_type']
        historyTime = local_time
        cur = self.conn.cursor()
        sql = "insert into zzh_history (user_id,user_ip,history_keywords,history_type,history_time) VALUES (%s,%s,%s,%s,%s)"
        rs = cur.execute(sql, [user_id, user_ip, history_keyword, history_type,historyTime])
        self.conn.commit()
        cur.close()
        self.conn.close()
        return rs

    def update_his(self, user_id, his_info):
        user_ip = his_info['user_ip']
        history_keyword = his_info['history_keyword']
        history_type = his_info['history_type']
        cur = self.conn.cursor()
        sql = "update zzh_history set user_ip=%s,history_keywords=%s,history_type=%s WHERE user_id=%s"
        rs = cur.execute(sql, [user_ip, history_keyword, history_type, user_id])
        return rs

    def query_his(self, user_id):
        cur = self.conn.cursor()
        sql = "select * from zzh_history WHERE user_id=%s AND history_status=1 ORDER BY history_time DESC limit 5"
        rs = cur.execute(sql, [user_id])
        his_list = cur.fetchall()
        his_json = Table2Json.history_list_to_json(his_list)
        return his_json

    def logicDelete(self,historyId,userId):
        """
        逻辑删除，将history_status设置为-1，表示此条记录已被删除。
        :param historyId:
        :param userId:
        :return:
        """
        cur = self.conn.cursor()
        historyStatus='-1'
        sql = "update zzh_history set history_status=%s WHERE user_id=%s AND history_id=%s"
        rs = cur.execute(sql, [historyStatus, userId,historyId])
        if rs:
            return 1
        else:
            return 0
